package com.chucang.shucang.usr.service.impl;

import cn.hutool.core.util.DesensitizedUtil;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.chucang.shucang.common.base.constant.CommonConstant;
import com.chucang.shucang.common.base.exception.FastException;
import com.chucang.shucang.common.base.service.impl.CrudServiceImpl;
import com.chucang.shucang.common.base.utils.OpsUtil;
import com.chucang.shucang.common.base.utils.R;
import com.chucang.shucang.common.base.utils.Sm4Util;
import com.chucang.shucang.usr.constant.UsrCommonConstant;
import com.chucang.shucang.usr.dao.RealNameAuthDao;
import com.chucang.shucang.usr.dto.RealNameAuthDTO;
import com.chucang.shucang.usr.entity.RealNameAuthEntity;
import com.chucang.shucang.usr.entity.UserBaseEntity;
import com.chucang.shucang.usr.feign.TtpService;
import com.chucang.shucang.usr.feign.vo.CreateAccountDTO;
import com.chucang.shucang.usr.feign.vo.IdCardInfoVO;
import com.chucang.shucang.usr.feign.vo.RealNameAuthResVO;
import com.chucang.shucang.usr.service.RealNameAuthService;
import com.chucang.shucang.usr.service.UserBaseService;
import com.chucang.shucang.usr.vo.RealNameAuthInfoResVO;
import com.chucang.shucang.usr.vo.RealNameAuthVO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Objects;


/**
 * 用户实名认证信息
 *
 * @author flitsneak flitsneak@gmail.com
 * @since 1.0.0 2022-09-12
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class RealNameAuthServiceImpl extends CrudServiceImpl<RealNameAuthDao, RealNameAuthEntity, RealNameAuthDTO> implements RealNameAuthService {

    private final UserBaseService userBaseService;
    private final TtpService ttpService;

    @Value("${encrypt.secret.sm4}")
    private String sm4;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public RealNameAuthInfoResVO doAuth(RealNameAuthVO realNameAuthVO) {
        //查询是否已实名
        UserBaseEntity byId = userBaseService.getById(realNameAuthVO.getUserId());
        if (Objects.isNull(byId)) {
            log.error("数据库查询用户：{} 异常！", realNameAuthVO.getUserId());
            throw new FastException("数据库查询异常！");
        }
        if (byId.getIsRealAuth() == UsrCommonConstant.REAL_NAME_AUTH) {
            RealNameAuthInfoResVO realNameAuthInfoResVO = new RealNameAuthInfoResVO();
            realNameAuthInfoResVO.setRealName(DesensitizedUtil.chineseName(realNameAuthVO.getRealName()));
            realNameAuthInfoResVO.setIdentityCard(DesensitizedUtil.idCardNum(realNameAuthVO.getIdentityCard(), 1, 1));
            return realNameAuthInfoResVO;
        }
        //未实名 开始认证
        R<RealNameAuthResVO> r = ttpService.doAuth(realNameAuthVO);
        RealNameAuthResVO authResVO = OpsUtil.of(r)
                .assertDataNotNull(e -> new FastException("获取实名认证信息异常"))
                .getData()
                .get();
        if (authResVO.getResult().getIsok().equals(UsrCommonConstant.REAL_NAME_AUTH_SUCCESS)) {
            //实名认证成功
            IdCardInfoVO idCardInfor = authResVO.getResult().getIdCardInfor();
            log.info("实名认证成功：{}", idCardInfor);
            RealNameAuthEntity realNameAuthEntity = new RealNameAuthEntity();
            realNameAuthEntity
                    .setSex(idCardInfor.getSex().equals("男") ? 1 : 0)
                    .setProvince(idCardInfor.getProvince())
                    .setCity(idCardInfor.getCity())
                    .setDistrict(idCardInfor.getDistrict())
                    .setArea(idCardInfor.getArea())
                    .setBirthday(idCardInfor.getBirthday())
                    .setRealName(Sm4Util.encode(sm4, realNameAuthVO.getRealName()))
                    .setIdentityCard(Sm4Util.encode(sm4, realNameAuthVO.getIdentityCard()))
                    .setUserId(realNameAuthVO.getUserId());
            this.save(realNameAuthEntity);
            //创建链地址账户
            R<CreateAccountDTO> account = ttpService.createAccount(byId.getCellPhoneNum(), byId.getId().toString());
            CreateAccountDTO accountDTO = OpsUtil.of(account)
                    .assertCode(CommonConstant.SUCCESS, e -> new FastException("创建链地址异常！"))
                    .getData()
                    .get();

            LambdaUpdateWrapper<UserBaseEntity> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.eq(UserBaseEntity::getId, realNameAuthVO.getUserId())
                    .set(UserBaseEntity::getIsRealAuth, UsrCommonConstant.REAL_NAME_AUTH)
                    .set(UserBaseEntity::getOffshoreAccount, accountDTO.getAccount())
                    .set(UserBaseEntity::getOffshoreAccountName, accountDTO.getName());
            userBaseService.update(updateWrapper);

            RealNameAuthInfoResVO realNameAuthInfoResVO = new RealNameAuthInfoResVO();
            realNameAuthInfoResVO.setRealName(DesensitizedUtil.chineseName(realNameAuthVO.getRealName()));
            realNameAuthInfoResVO.setIdentityCard(DesensitizedUtil.idCardNum(realNameAuthVO.getIdentityCard(), 1, 1));
            return realNameAuthInfoResVO;
        }
        log.warn("实名认证失败！");
        return null;
    }
}